/* eslint-disable */

const fs = require('fs');
const path = require('path');
const util = require('util');

const config = require('config').get('deploy');
const BosClient = require('bce-sdk-js').BosClient;

const bucket = config.bucket;
const client = new BosClient(config);

const rebuildUrl = filePath => {
    try {
        const content = fs.readFileSync(filePath, {encoding: 'utf8'});

        fs.writeFileSync(
            filePath,
            content.replace(
                new RegExp(config.viewKey, 'g'),
                `${config.cdnUrl}/${config.module}`
            )
        );
    }
    catch (err) {
        console.error('[deploy ERROR]' + util.inspect(err));
    }
};

const uploadFile = async (destPath, filePath) => {
    try {
        await client.putObjectFromFile(bucket, `${config.module}/${destPath}`, filePath);
        return null;
    }
    catch (err) {
        console.log('[deploy ERROR]' + util.inspect(err));
    }
};

const main = async () => {
    rebuildUrl(path.resolve(config.viewDir + '/index.app.ejs'));

    const dirPath = config.distDir;
    const dir = fs.readdirSync(dirPath);
    const files = fs.readdirSync(`${dirPath}/${dir[0]}`);
    const updates = await Promise.all(
        files.map(file => {
            const filePath = path.resolve(dirPath, dir[0], file);
            const extName = path.extname(filePath);

            if (extName === '.css') {
                // css 中的某些静态资源路径也改掉
                rebuildUrl(filePath);
            }

            return uploadFile(`${dir[0]}/${file}`, filePath);
        })
    );

    console.log(`[SUCCESS] Publish to Bos Completed. Updated ${updates.length} files.`);
};

main();
